package tsvetanv.inventory.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import tsvetanv.inventory.model.Article;
import tsvetanv.inventory.service.ArticleService;

/**
 * The <code>ArticleEditFormController</code> is related with processing
 * pipeline of the <b>EditArticle HTML Form</b>.
 *
 * @author Tsvetan Vasilev
 *
 */
public class ArticleEditFormController extends SimpleFormController {

	@Autowired
	private ArticleService articleService;

	// private static Logger logger = Logger
	// .getLogger(ArticleEditFormController.class);

	// --- Constructors, Getters, Setters --------------------------------------
	public ArticleEditFormController() {
		setCommandName("article");
		setCommandClass(Article.class);
		setFormView("/articleEditForm");
		setSuccessView("redirect:/articles/home");
	}

	public void setArticleService(ArticleService articleService) {
		this.articleService = articleService;
	}

	// --- Methods -------------------------------------------------------------

	@Override
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		super.initBinder(request, binder);

		// rudimental fields validation
		binder.setRequiredFields(new String[] { "product.name",
				"product.description", "quantity" });
	}

	@Override
	protected ModelAndView onSubmit(Object command) throws Exception {
		Article article = (Article) command;
		// persist article
		if (article.getId() > 0) {
			// useCase: UPDATE article
			articleService.update(article);
		} else {
			// useCase: SAVE article
			articleService.save(article);
		}

		// prepare success view
		ModelAndView modelAndView = new ModelAndView(getSuccessView());
		modelAndView.addObject("articles", articleService.getAllArticles());
		return modelAndView;
	}

	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		String articleId = request.getParameter("id");
		if (articleId == null || articleId.isEmpty()) {
			return super.formBackingObject(request);
		} else {
			Article article = articleService.findByArticleId(Integer
					.valueOf(articleId));
			return (Object) article;
		}
	}
}
